package cn.itcast.nems.common.validator;

import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 校验
 * </p>
 *
 * @author zhouwei
 * @since 2023/9/23 10:10 AM
 **/
public class CustomerValidator<T> {

    /*** 初始化为 true  true &&其它布尔值时由其它布尔值决定真假*/
    private Predicate<T> predicate = t -> true;

    /***
     * 添加一个校验策略，可以无限循环
     * @param predicate the predicate*
     * @return the validator
     * */
    public CustomerValidator<T> with(Predicate<T> predicate) {
        this.predicate = this.predicate.and(predicate);
        return this;
    }

    /***
     * 添加一个【或】校验策略，可以无限循环
     * @param predicate the predicate*
     * @return the validator
     * */
    public CustomerValidator<T> or(Predicate<T> predicate) {
        this.predicate = this.predicate.or(predicate);
        return this;
    }

    /*** 执行校验
     * @param t 校验对象, 可以是集合、数组、对象等
     * @return the boolean
     * */
    public boolean validate(T t) {
        return predicate.test(t);
    }


    /****
     * key 去重
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        // 这个局部变量必须定义，这个局部变量将会成为下面生成的局部匿名内部类的一个字段（field）
        final Set<Object> seen = ConcurrentHashMap.newKeySet();
        // 用 lambda 来代替匿名内部类
        return t -> seen.add(keyExtractor.apply(t));
    }

    public static void main(String[] args) {
        // System.out.println(new CustomerValidator<String>().with(StringUtils::hasText).validate("1121212"));
        // System.out.println(Arrays.stream(new String[]{"1", "2", "3", "11", "2223", "s", "1", "22"}).toList().stream().filter(distinctByKey(String::toString)).collect(Collectors.toList()));
        System.out.println(Arrays.stream(new String[]{"1", "2", "3", "11", "2223", "s", "1", "22"}).toList().stream().distinct().collect(Collectors.toList()));
    }

}